package com.eastfair.certificate.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eastfair.certificate.dto.BlacklistDTO;
import com.eastfair.certificate.entity.Blacklist;
import com.eastfair.certificate.dto.BlacklistSaveDTO;
import com.eastfair.certificate.dto.BlacklistUpdateDTO;
import com.eastfair.certificate.dto.BlacklistPageQuery;
import com.eastfair.certificate.enumeration.BlacklistKindEnum;
import com.eastfair.certificate.service.BlacklistService;

import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.eastfair.boot.controller.SuperController;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.eastfair.certificate.vo.BlacklistVO;
import com.eastfair.certificate.vo.CertificateUserVO;
import com.eastfair.core.utils.StrPool;
import com.eastfair.database.mybatis.typehandler.TypeHandlerUtil;
import com.eastfair.echo.core.EchoService;
import com.eastfair.core.base.R;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.eastfair.annotation.annotation.security.PreAuth;

import com.eastfair.boot.request.PageParams;
import com.eastfair.core.context.ContextUtil;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;


/**
 * <p>
 * 前端控制器
 *
 * </p>
 *
 * @author clm
 * @date 2022-08-02
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/blacklist")
@Api(value = "Blacklist", tags = "")
@PreAuth(replace = "certificate:blacklist:")
public class BlacklistController extends SuperController<BlacklistService, Long, Blacklist, BlacklistPageQuery, BlacklistSaveDTO, BlacklistUpdateDTO> {

    @Autowired
    private EchoService echoService;
    @Autowired
    private BlacklistService blacklistService;

    @Override
    public void handlerResult(IPage<Blacklist> page) {
        // 想让返回值实现自动回显，请将此行代码打开
        // echoService.action(page);
    }

    /**
     * Excel导入后的操作
     *
     * @param list
     */
    @Override
    public R<Boolean> handlerImport(List<Map<String, String>> list) {
        List<Blacklist> blacklistList = list.stream().map((map) -> {
            Blacklist blacklist = Blacklist.builder().build();
            //TODO 请在这里完成转换
//            BeanUtil.mapToBean(map, Blacklist.class, false, new CopyOptions());
            Object userName = map.get("姓名");
            Object cardNumber = map.get("身份证号码");
            Object mobile = map.get("手机号");
//            Object companyName = map.get("公司名称");
            blacklist.setUserName(String.valueOf(userName));
            blacklist.setCardNumber(String.valueOf(cardNumber));

            Double t = Double.valueOf(String.valueOf(mobile));
            BigDecimal phone = new BigDecimal(t);
//            System.out.println(phone);
            blacklist.setPhoneNumber(String.valueOf(phone));
//            blacklist.setCompanyName(String.valueOf(companyName));
            blacklist.setKind(BlacklistKindEnum.POLICE);
            return blacklist;
        }).collect(Collectors.toList());

        for (Blacklist blacklist : blacklistList) {
            //查询是否存在
            BlacklistDTO blacklistDTO1 = new BlacklistDTO();
            BeanUtils.copyProperties(blacklist, blacklistDTO1);
            blacklistDTO1.setRemark(null);
            List<Blacklist> blacklists = blacklistService.list(blacklistDTO1, null);
            if (CollectionUtil.isEmpty(blacklists)) {
                blacklistService.addBlack(blacklist);
            }
        }
//        baseService.saveBatch(blacklistList)


        return R.success();
    }


    /**
     * 处理参数
     *
     * @param params 分页参数
     */
    @Override
    public void handlerQueryParams(PageParams<BlacklistPageQuery> params) {
        BlacklistPageQuery pageQuery = params.getModel();
        //分页处理
        if (ContextUtil.getProjectId() != null) {
            pageQuery.setProjectId(ContextUtil.getProjectId());
        }
        //加密处理
//        if(StringUtils.isNotBlank(pageQuery.getCardNumber())){
//            pageQuery.setCardNumber(TypeHandlerUtil.crypt(pageQuery.getCardNumber()));
//        }
//        if(StringUtils.isNotBlank(pageQuery.getPhoneNumber())){
//            pageQuery.setPhoneNumber(TypeHandlerUtil.crypt(pageQuery.getPhoneNumber()));
//        }

    }

    /**
     * @return
     * @Author clm
     * @Description 黑名单列表
     * @Date 11:17 2022/8/2
     * @Param [query]
     **/
    @PostMapping("/queryPage")
    public R<Page<BlacklistVO>> queryPage(@RequestBody @Validated PageParams<BlacklistPageQuery> params) {
        return R.success(blacklistService.queryPage(params));
    }

    /**
     * @return com.eastfair.core.base.R
     * @Author clm
     * @Description //取消
     * @Date 11:54 2022/8/2
     * @Param [blackId]
     **/
    @GetMapping("/cancel/{blackId}")
    public R cancel(@PathVariable("blackId") Long blackId) {
        blacklistService.cancel(blackId);
        return R.success();
    }

    /**
     * @return com.eastfair.core.base.R
     * @Author 李刚
     * @Description //移除黑名单
     * @Date 11:54 2022/8/2
     * @Param [blackId]
     **/
    @PostMapping("/remove")
    public R remove(@RequestBody BlacklistDTO blacklistDTO) {
        blacklistService.removeBlack(blacklistDTO.getIds());
        return R.success();
    }

    //表格导出接口
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws IOException {
        //在内存操作，写到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //自定义标题别名
        writer.addHeaderAlias("userName", "姓名");
        writer.addHeaderAlias("cardNumber", "身份证号码");
        writer.addHeaderAlias("mobile", "手机号");
//        writer.addHeaderAlias("companyName", "公司名称");
        List<JSONObject> list = new ArrayList();
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("userName", "1");
        jsonObject.set("cardNumber", "1");
        jsonObject.set("mobile", "1");
//        jsonObject.set("companyName", "1");
        list.add(jsonObject);

        writer.write(list, true);
        //设置content—type
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset:utf-8");
        //设置标题
        String fileName = URLEncoder.encode("黑名单信息", "UTF-8");
        //Content-disposition是MIME协议的扩展，MIME协议指示MIME用户代理如何显示附加的文件。
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
        ServletOutputStream outputStream = response.getOutputStream();

        //将Writer刷新到OutPut
        writer.flush(outputStream, true);
        outputStream.close();
        writer.close();
    }


}
